package com.prb.proivder.one.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.prb.common.protocol.RpcResponse;
import com.prb.common.protocol.RpcRequest;
import com.prb.common.protocol.SmartCarProtocol;
import com.prb.proivder.one.service.UserServiceImpl;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

public class RequestHandler extends ChannelInboundHandlerAdapter {
    // 用于获取客户端发送的信息
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {

        // 用于获取客户端发来的数据信息
        SmartCarProtocol body = (SmartCarProtocol) msg;
        RpcRequest rpcRequest = JSONObject.parseObject(new String(body.getContent()) , RpcRequest.class);

        //调用服务
        Object obj = invokeService(rpcRequest);

        RpcResponse rpcResponse = new RpcResponse(rpcRequest.getInvokeId() , null  , obj);
        SmartCarProtocol response = new SmartCarProtocol(JSON.toJSONString(rpcResponse).getBytes().length,
                JSON.toJSONString(rpcResponse).getBytes());
        // 当服务端完成写操作后，关闭与客户端的连接
        ctx.writeAndFlush(response);

    }

    private Object invokeService(RpcRequest rpcRequest) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class cls = rpcRequest.getClazz();
        Class[] params = rpcRequest.getParamTypes();
        List<Object> args = rpcRequest.getArgs();
        String methodName = rpcRequest.getMethodName();

        Method method = cls.getMethod(methodName, params);

        return method.invoke(new UserServiceImpl() , args.get(0));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        // cause.printStackTrace();
        ctx.close();
    }
}